// pages/ecergency/ecergency.js
var app = getApp()
var dateTimePicker = require('../../utils/dateTimePicker.js');
var util = require('../../utils/util.js')  
Page({

  /**
   * 页面的初始数据
   */
  data: {
    multiArray:[],
    id:0,
    multiIndex:[0,1],
    xiaoquList:[],
    xiaoquArr:[],
    classList:[],
    classArr:[],
    class_id:[],
    dateTime: '',
    dateTimeArray: null,
    title:'',
    place:'',
    dead:0,
    vimtem:0,
    dateTime1:'',
    typeId:'',
    typeName:'',
    topTypeId:'',
    topTypeName:'',
    hiddenName:true,
    feeds:[],
    array: ['1', '2', '3', '4'],
    objectArray: [
      {
        id: 0,
        name: '1'
      },
      {
        id: 1,
        name: '2'
      },
      {
        id: 2,
        name: '3'
      },
      {
        id: 3,
        name: '4'
      }
    ],
    index: 0,
    eventLevel:0,
      //标签页
      activeTab:'新建事件',
      //事件的历史纪录
      eventList:[],
      eventTotal:0,
      noDataHide:false,
      eventListCurrentPage:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
    });

    var header;
    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    var that = this
    wx.request({
      url: app.globalData.baseUrl +'/safe/emgType/getAll/2',
      method: 'get',
      // data: {},
      header: header,
      success:function(res) {
        console.log(res.data.data);
        var xiaoquList = res.data.data;
        var xiaoquArr = xiaoquList.map(item => {　　　　// 此方法将校区名称区分到一个新数组中
          return item.typeName;
         });
        console.log(xiaoquArr);
        that.setData({
          multiArray: [xiaoquArr, []],
          xiaoquList,
          xiaoquArr
        })
        var default_id = xiaoquList[0]['id'];
        console.log(default_id);
        if (default_id) {
          that.searchClassInfo(default_id)
        }
      }
    })   
  },

  onChange(event) {
    // event.detail 为当前输入的值
    // console.log(event.detail);
    this.setData({
      title:event.detail
    })
  },

  onChange1(event) {
    // event.detail 为当前输入的值
    // console.log(event.detail);
    this.setData({
      place: event.detail
    })
  },

  onChange2(event) {
    // event.detail 为当前输入的值
    // console.log(event.detail);
    this.setData({
      dead: event.detail
    })
  },

  onChange3(event) {
    // event.detail 为当前输入的值
    // console.log(event.detail);
    this.setData({
      vimtem: event.detail
    })
  },

  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    this.setData({
      index: e.detail.value
    })
    console.log(this.data.array[this.data.index]);
    this.data.eventLevel = this.data.array[this.data.index];
  },

  searchClassInfo(shijian_id) {
    var header;
    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    var that = this;
    if (shijian_id) {
      this.setData({
        id: shijian_id
      })
      wx.request({
        url: app.globalData.baseUrl + '/safe/emgType/getAll/2',
        method: 'get',
        header: header,
        success:function(res){
          var shijianList = res.data.data;
          for (var item in shijianList){
            if (shijianList[item].id==that.data.id){
              // console.log(that.data.id);
              var classList=shijianList[item]["subTypes"];
              // console.log(subList);
              var classArr = classList.map(item => {
                return item.typeName;
              })
              console.log(classArr);
              var xiaoquArr = that.data.xiaoquArr;
              that.setData({
                multiArray: [xiaoquArr, classArr],
                classList,
                classArr
              })
              console.log(that.data.multiArray);
            }
          }
        }
      })
    }
  },

  changeDateTime(e) {
    this.setData({ dateTime: e.detail.value });
    console.log(this.data.dateTime);
    var dataTime10 = this.data.dateTime[0].toString();
    var dataTime11 = this.data.dateTime[1].toString();
    var dataTime12 = this.data.dateTime[2].toString();
    var dataTime1 = dataTime10+dataTime11+dataTime12;
    // var dataTime2=
    // console.log(dataTime2);
    var dateObj = new Date();
    dateObj.setTime(dataTime1);
    var dataTime11 = util.formatTime(dateObj);
    // console.log(dataTime11);
     var dataTime12 = this.data.dateTimeArray[0][this.data.dateTime[0]]
      + '-' + this.data.dateTimeArray[1][this.data.dateTime[1]] + '-' + this.data.dateTimeArray[2][this.data.dateTime[2]] + ' ' + this.data.dateTimeArray[3][this.data.dateTime[3]] + ':' + this.data.dateTimeArray[4][this.data.dateTime[4]] + ':' + this.data.dateTimeArray[5][this.data.dateTime[5]]
    console.log(this.data.dataTime1);
    var timestamp2 = Date.parse(new Date(dataTime12));
    this.setData({
      dataTime1:timestamp2 / 1000
    })
    console.log(this.data.dataTime1);
  },

  changeDateTimeColumn(e) {
    var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr
    });
  },

  bindMultiPickerColumnChange: function (e) {
    //e.detail.column 改变的数组下标列, e.detail.value 改变对应列的值
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    var teach_area_id_session = this.data.id;　　　　// 保持之前的校区id 与新选择的id 做对比，如果改变则重新请求数据
    switch (e.detail.column) {
      case 0:
        var xiaoquList = this.data.xiaoquList;
        var teach_area_id = xiaoquList[e.detail.value]['id'];
        if (teach_area_id_session != teach_area_id) {　　　　// 与之前保持的校区id做对比，如果不一致则重新请求并赋新值
          this.searchClassInfo(teach_area_id);
        }
        data.multiIndex[1] = 0;
        break;
    }
    this.setData(data);
    console.log(data.multiIndex[e.detail.column]);
  },

  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var class_key = 0;
    var classList = this.data.classList;
    var select_key = e.detail.value[1];
    var real_key = select_key - 1;
    if (real_key < class_key) {
      this.setData({
        class_id: 0
      })
    } else {
      this.setData({
        class_id: classList[real_key]['id']　　　　　　// class_id 代表着选择的班级对应的 班级id
      })
    }
    this.setData({
      multiIndex: e.detail.value
    })
    var shijiantoptype = this.data.multiArray[0][this.data.multiIndex[0]];
    var shijiantype = this.data.multiArray[1][this.data.multiIndex[1]];
    console.log(shijiantoptype);
    console.log("shijiantype="+shijiantype);
    for(var item in this.data.xiaoquList){
      console.log(this.data.xiaoquList[item].typeName);
      if (this.data.xiaoquList[item].typeName==shijiantoptype){
        this.setData({
          topTypeId: this.data.xiaoquList[item]['id']
        })
        // this.data.topTypeId = this.data.xiaoquList[item]['id'];
      }
    }
    console.log(this.data.topTypeId);
    for (var item in this.data.classList) {
      if (shijiantype!='undefined'){
        if (this.data.classList[item].typeName == shijiantype) {
          this.setData({
            typeId: this.data.classList[item]['id']
          })
        }
      }
    }
    console.log("id="+this.data.typeId);
    // console.log(this.data.shijiantype);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  clickButton:function(){
    var that = this;
    this.setData({
      hiddenName: false
    })
    var header;
    header = {
      'Cookie': wx.getStorageSync("sessionid"), //读取cookie
      'content-type': 'application/json'
    };
    var shijiantoptype = that.data.multiArray[0][that.data.multiIndex[0]];
    var shijiantype = that.data.multiArray[1][that.data.multiIndex[1]];
    for (var item in that.data.xiaoquList) {
      console.log(that.data.xiaoquList[item].typeName);
      if (that.data.xiaoquList[item].typeName == shijiantoptype) {
        that.setData({
          topTypeId: that.data.xiaoquList[item]['id']
        })
        // this.data.topTypeId = this.data.xiaoquList[item]['id'];
      }
    };

    for (var item in that.data.classList) {
      if (shijiantype != 'undefined') {
        if (that.data.classList[item].typeName == shijiantype) {
          this.setData({
            typeId: that.data.classList[item]['id']
          })
        }
      }
    };

    var dataTime12 = that.data.dateTimeArray[0][that.data.dateTime[0]]
      + '-' + that.data.dateTimeArray[1][that.data.dateTime[1]] + '-' + that.data.dateTimeArray[2][that.data.dateTime[2]] + ' ' + that.data.dateTimeArray[3][that.data.dateTime[3]] + ':' + that.data.dateTimeArray[4][that.data.dateTime[4]] + ':' + that.data.dateTimeArray[5][that.data.dateTime[5]]
    console.log(that.data.dataTime1);
    var timestamp2 = Date.parse(new Date(dataTime12));
    that.setData({
      dataTime1: timestamp2 / 1000
    })



    var params = {
      blockLength: 0,
      blockLengthUnit:'米',
      chemicalLeakage:'',
      chemicalName: '',
      dangerousChemical:0,
      dangerousChemicalType:'',
      deathNum:that.data.dead,
      econLoss:0,
      eventTime: new Date(that.data.dataTime1),
      eventTitle: that.data.title,
      injuriesNum: that.data.vimtem,
      interruptTime:0,
      interruptTimeUnit:'天',
      interruptType:'',
      location: that.data.place,
      pileDirection:'',
      pileK:'',
      pileM:'',
      topTypeId: that.data.topTypeId,
      typeId: that.data.typeId
    }
    if(that.data.dead==''){
      that.data.dead=0;
    }
    if (that.data.vimtem == '') {
      that.data.vimtem = 0;
    }
    wx.request({
      url: app.globalData.baseUrl + '/safe/emgEvent/countEventLevel',
      // data: '',
      header: header,
      data: params,
      method: 'post',
      // dataType: 'json',
      // responseType: 'text',
      success: function(res) {
        console.log("请求成功")
      },
      fail: function(res) {

      },
      complete: function(res) {
        var header;
        console.log(that.data.topTypeId);
        console.log(that.data.typeId);
        header = {
          'Cookie': wx.getStorageSync("sessionid"), //读取cookie
          'content-type': 'application/json'
        };
        var params = {
          topTypeId: that.data.topTypeId,
          typeId: that.data.typeId,
          pageCurrent: 1,
          pageSize: 8
        }
        wx.request({
          url: app.globalData.baseUrl + '/safe/emgHandle/find',
          header: header,
          data:params,
          method: 'POST',
          success: function (res) {
            console.log("请求成功");
            var result = res.data.data.list;
            console.log(result);
            that.setData({
              feeds:result
            })
            console.log(that.data.feeds);
          },
          fail: function (res) {

          },
        })
      },
      // },
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.activeTab==='事件列表'){//事件列表页面才触发搜索
        if(this.data.eventList.length<this.data.eventTotal){
            this.getEmergencyEventList(this.data.eventListCurrentPage+1)
        }else{
            wx.showToast({
                title: '已全部加载',
                icon: 'success',
                duration: 1000
            })
        }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getDate: function (e) {
    console.log(e.detail)
  },
  ecergencyDetail: function (e) {
    var that = this;
    var abc = e.currentTarget.dataset.abc;
    //console.log(abc);
    var header;
    header = {
      'Cookie': wx.getStorageSync("sessionid"), //读取cookie
      'content-type': 'application/json'
    };
    var params = {
      blockLength:0,
      blockLengthUnit:"米",
      chemicalLeakage:"",
      chemicalName:"",
      companyId:null,
      createTime:null,
      createUserId:null,
      createUserName:null,
      dangerousChemical:null,
      dangerousChemicalType:"",
      deathNum:that.data.dead,
      deptCode:null,
      deptId:null,
      deptName:null,
      econLoss:0,
      endDate:null,
      eventTime: that.data.dataTime1,
      eventTitle:that.data.title,
      id:null,
      injuriesNum:that.data.vimtem,
      interruptTime:0,
      interruptTimeUnit:"天",
      interruptType:"",
      location:"",
      num:null,
      pageCurrent:1,
      pageSize:10,
      pages:0,
      pileDirection:"",
      pileK:"",
      pileM:"",
      reported:null,
      sortField:null,
      sortOrder:"desc",
      start:0,
      startDate:null,
      status:null,
      topTypeName:null,
      total:0,
      typeName:null,
      eventLevel:that.data.eventLevel,
      topTypeId: that.data.topTypeId,
      typeId: that.data.typeId,
      handleId:abc
    };
    if (this.data.title!=''){
      wx.request({
        url: app.globalData.baseUrl + '/safe/emgEvent/add',
        header: header,
        data: params,
        method: 'POST',
        success: function (res) {
          console.log("请求成功");
          var eventId=res.data.data.event.id;
          if(eventId!=''){
            console.log(eventId);
            wx.navigateTo({
              url: '/pages/ecergency/ecergencydetail/ecergencydetail?eventId=' + eventId,
            })
          }
          // var result = res.data.data.list;
          // console.log(result);
          // that.setData({
          //   feeds: result
          // })
          // console.log(that.data.feeds);
        },
        fail: function (res) {

        },
      })
    }

    // wx.navigateTo({
    //   url: '/pages/duty/dutydetail/dutydetail?companyId=' + companyId + '&dutyTypeCode=' + abc + '&year=' + bcd,
    // })
  },

    //事件列表标签页触发事件
    eventListClick:function (event) {
      if(event.detail.title==='事件列表'){
        this.setData({
            activeTab:'事件列表'
        });
          this.getEmergencyEventList(1)
      }else{
          this.setData({
              activeTab:'新建事件'
          });
      }
    },
    //获取应急事件列表
    getEmergencyEventList:function (currentPage) {
        this.setData({
            eventListCurrentPage:currentPage
        })
        let that = this
        let header;
        header = {'Cookie': wx.getStorageSync("sessionid")};
        let params={pageCurrent:this.data.eventListCurrentPage};
        wx.showLoading()
        wx.request({
            url: app.globalData.baseUrl + '/safe/emgEvent/find',
            header: header,
            method: "POST",
            data: params,
            success(res) {
                if(res.data.data.list.length){
                    let tempArr=res.data.data.list;
                    tempArr.forEach(function (item) {
                        let dateObj=new Date();
                        dateObj.setTime(item.createTime);
                        item.createDateStr=util.formatTimeHour(dateObj);
                        item.statusStr=item.status?'已完结':'进行中';
                        item.operateStr=item.status?'查看':'记录';
                    });
                    let resultArr=that.data.eventList;
                    that.setData({
                        eventList:resultArr.concat(tempArr),
                        eventTotal:res.data.data.total,
                        noDataHide:true
                    });
                }else {
                    that.setData({
                        eventList: [],
                        eventTotal:0,
                        noDataHide:false
                    });
                }
                //关闭加载
                wx.hideLoading()
            },
            fail(){
                //关闭加载
                wx.hideLoading()
                wx.showToast({
                    title: '加载数据失败',
                    icon: 'none',
                    duration: 1000
                })
            }
        })
    },

    //编辑应急事件
    editClick:function (event) {
      if(event.currentTarget.dataset.status){//已完结的事件，进入查看
          wx.navigateTo({
              url: '/pages/ecergency/viewEvent/viewEvent?eventId=' + event.currentTarget.dataset.id + '&title=' + event.currentTarget.dataset.name,
          })
      }else{//进行中的事件，进入编辑
          wx.navigateTo({
              url: '/pages/ecergency/editEvent/editEvent?eventId=' + event.currentTarget.dataset.id + '&title=' + event.currentTarget.dataset.name,
          })
      }
    }

})